<?php
/**
 * Created by PhpStorm.
 * User: shutao
 * Date: 2018/9/22
 * Time: 12:34
 */

namespace wechat\services;

use ttcommon\base\Data;
use wechat\models\WeContent;
use yii\base\UserException;

class WeContentService
{
    /**
     * 通过主键查询指定模板
     * @param integer $id
     * @param null|string $field 查询的字段名
     * @return array|null|string
     */
    public static function find($id, $field = null)
    {
        $row = WeContent::find()->where(['id' => $id])->select($field ? [$field] : ['id', 'title', 'type', 'content'])->asArray()->one();
        return $field ? Data::hasValue($row, $field) : $row;
    }

    /**
     * 通过关键词查询回复的内容
     * @param string $keyword 关键词
     * @return string 未替换变量的内容
     * @throws UserException
     */
    public static function contentByKeyword($keyword)
    {
        static $cache = [];
        if (!isset($cache[$keyword])) {
            if (!$record = WeContent::find()->where(['keyword' => $keyword])->select(['content'])
                ->asArray()->one()) {
                throw new UserException('关键词[' . $keyword . ']没有内容');
            }
            $cache[$keyword] = $record['content'];
        }
        return $cache[$keyword];
    }

    /**
     * 替换内容中的变量，如果还需要过滤掉 html 标记，可以使用 strip_tags($content,'<br>')
     * @param string $content 内容，可以通过 self::contentByKeyword 查找
     * @param array $varParams 替换 $content 中的变量
     * @param array $systemParams 替换系统变量（默认为空，使用系统内置的变量）
     * @return string
     */
    public static function replaceContent($content, $varParams, $systemParams = [])
    {
        if ($content) {
            $replaces = [];
            $systemVars = [];
            preg_match_all('#<span class="wechat_var_system_(\w+)">[^<]+</span>#', $content, $systemVars);
            if ($systemVars) {
                foreach ($systemVars[1] as $key => $name) {
                    if (isset($systemParams[$name])) {
                        $replaceTo = $systemParams[$name];
                    } else {
                        $info = WeSystemVar::vars($name);
                        $replaceTo = isset($info['value']) ? $info['value'] : Data::hasValue($info, 1, '');
                    }

                    $replaces[] = [$systemVars[0][$key], $replaceTo];
                }
            }
            $tplVars = [];
            preg_match_all('#<span class="wechat_var_tpl_(\w+)">[^<]+</span>#', $content, $tplVars);
            if ($tplVars) {
                foreach ($tplVars[1] as $key => $name) {
                    $replaces[] = [$tplVars[0][$key], isset($varParams[$name]) ? $varParams[$name] : ''];
                }
            }

            if ($replaces) {
                foreach ($replaces as $r) {
                    $content = str_replace($r[0], $r[1], $content);
                }
            }
        }
        return $content;
    }
}